import axios from 'axios'
import Vue from 'vue'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import router from '../router'
import { getToken } from '@/utils/auth'
import { encrypt, regexp } from "./tools"
import sha1 from 'js-sha1'

// import qs from 'qs'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的 base_url
  timeout: 1000 * 60 * 10 // 请求超时时间,
  // headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});


// request拦截器
service.interceptors.request.use(config => {
  // 设置同步操作超时时间
  if (config.url.match('syn') || config.url.match('Sync')) {
    config.timeout = 1000 * 60 * 60
  }
  if (config.url.match('/bsnl-oss/')) {
    config.baseURL = process.env.UPLOAD_BASE_API
  } else if (config.url.match('/api/commission') || config.url.match('api/customer')) {
    config.baseURL = process.env.MANAGER_COMMISSION
  }else if(config.url.match('/pop/')){
    config.baseURL = process.env.POP_MERCHANT_API
  } else if (config.url.match('/manager/commission')) {
    config.baseURL = process.env.MANAGER_GATEWAY_COMMISSION
  }

  if(config.apiType === 'commission'){
    //时间挫
    var stamp = new Date().getTime()
    //随机6位数
    var nonce = Math.floor(Math.random() * 999999)
    var bb = 'ojojioji:;;?@#-=UFJHFUfehu!SNJHUFp[][d' + stamp + nonce
    var sign = sha1(bb)
    config.headers['sign'] = sign
    config.headers['stamp'] = stamp
    config.headers['nonce'] = nonce
    config.baseURL = process.env.MANAGER_GATEWAY_COMMISSION
  }

  /* if (config.url.match('/bsnl-activity/')) {
    config.baseURL = process.env.ACTIVITY_BASE_API
  } else if (config.url.match('/bsnl-authority/')) {
    config.baseURL = process.env.AUTHORITY_BASE_API
  } else if (config.url.match('/bsnl-ad/')) {
    config.baseURL = process.env.AD_BASE_API
  } else if (config.url.match('/welfare/')) {
    config.baseURL = process.env.WELFARE_BASE_API
  } else if (config.url.match('/bsnl-manage/')) {
    config.baseURL = process.env.MANAGE_BASE_API
  } else if (config.url.match('/bsnl-member/')) {
    config.baseURL = process.env.MEMBER_BASE_API
  } else if (config.url.match('/bsnl-order/')) {
    config.baseURL = process.env.ORDER_BASE_API
  } else if (config.url.match('/bsnl-product/')) {
    config.baseURL = process.env.PRODUCT_BASE_API
  } else if (config.url.match('/bsnl-box/')) {
    config.baseURL = process.env.BOX_BASE_API
  } else if (config.url.match('/mc-manage/')) {
    config.baseURL = process.env.MESSAGE_BASE_API
  } else if (config.url.match('erp-')) {
    config.baseURL = process.env.ERP_BASE_API
  } else if (config.url.match('/merchant/orderInfo/')) {
    config.baseURL = process.env.MERCHANT_ORDER_BASE_API
  } else if (config.url.match('/merchant/info/')) {
    config.baseURL = process.env.MERCHANT_BASE_API
  } else if (config.url.match('/finance/')) {
    config.baseURL = process.env.FINANCE_BASE_API
  } else if (config.url.match('bsnl-merchant-')) {
    config.baseURL = process.env.MERCHANT_OLD_BASE_API
  } else if (config.url.match('/sp/store/')) {
    config.baseURL = process.env.STORE_BASE_API
  } else if (config.url.match('/bi/')) {
    config.baseURL = process.env.BI_BASE_API
  } else if (config.url.match('/bsnl-oss/')) {
    config.baseURL = process.env.UPLOAD_BASE_API
  } else if (config.url.match('/goddess/')) {
    config.baseURL = process.env.GODDESS_BASE_API
  } else if (config.url.match('/bsnl-refund/')) {
    config.baseURL = process.env.REFUND_BASE_API
  } else if (config.url.match('/bsnl-goods-refund/')) {
    config.baseURL = process.env.GOODS_REFUND_BASE_API
  } else if (config.url.match('/coupon/')) {
    config.baseURL = process.env.COUPON_BASE_API
  } else if (config.url.match('/goods/activity/user/')) {
    config.baseURL = process.env.NEW_USER_AD_BASE_API
  } else if (config.url.match('/vplan/')) {
    config.baseURL = process.env.V_BASE_API
  } else if (config.url.match('/promotion')) {
    config.baseURL = process.env.PROMOTION
  } else if (config.url.match('/finance-common-service')) {
    config.baseURL = process.env.CONCILIATION_BASE_API
  } else if (config.url.match('/api/commission') || config.url.match('api/customer')) {
    config.baseURL = process.env.MANAGER_COMMISSION
  } else if (config.url.match('/lottery/system')) {
    config.baseURL = process.env.LOTTERY_SYSTEM
  } else if (config.url.match('/gb-manage/')) {
    config.baseURL = process.env.GB_MANAGE
  } else if (config.url.match('/acm/')) {
    config.baseURL = process.env.APP_CONFIG_BASE_API
  } else if (config.url.match('/sign-in/')) {
    config.baseURL = process.env.SIGN_IN_BASE_API
  } else if (config.url.match('/v1/freight/')) {
    // 新增模板链接
    config.baseURL = process.env.FREIGHT_TPL
  } else if (config.url.match('/bus-')) {
    config.baseURL = process.env.BUS_API
  } else if (config.url.match('/upgrade/app/')) {
    config.baseURL = process.env.ADVICE_BASE_API
  } else if (config.url.match('/v1/freight/')) {
    // 新增模板链接
    // config.baseURL = 'http://localhost:9528'
    config.baseURL = process.env.FREIGHT_TPL
  } else if (config.url.match('/bus-')) {
    config.baseURL = process.env.BUS_API
  } else if (config.url.match('/upgrade/app/')) {
    config.baseURL = process.env.ADVICE_BASE_API
  } else if (config.url.match('/bihs/')) {
    config.baseURL = process.env.BIHS_BASE_API
  } else if (config.url.match('/order-status/')) {
    config.baseURL = process.env.FIXED_API
  } else if (config.url.match("/evaluate-service/")) {
    config.baseURL = process.env.BX_COMMONT_API;
  } else if (config.url.match("-bzb-")) {
    config.baseURL = process.env.BZB_BASE_API;
  } else if (config.url.match('/live')) {
    config.baseURL = process.env.LIVE_BASE_API
  }
  else if (config.url.match('/bihs/')) {
    config.baseURL = process.env.BIHS_BASE_API
  } else if (config.url.match('/order-status/')) {
    config.baseURL = process.env.FIXED_API
  } else if (config.url.match("/evaluate-service/")) {
    config.baseURL = process.env.BX_COMMONT_API;
  }  else if (config.url.match("/vip-day/")) {
    config.baseURL = process.env.VIP_DAY_API
  }if (config.url.match('admin-web-api')) {
    // 商品中台服务
    config.baseURL = process.env.GOOOD_MIDDLESTAGE_API
  } else if (config.url.match("/manage-home-web/")) {
    config.baseURL = process.env.BI_XUAN5_API
  }  */

  const dataKey = config.method === 'get' ? 'params' : 'data'
  config[dataKey] = config[dataKey] || {}
  const userId = store.getters.userId;
  if (userId) {
    config.headers['userId'] = userId
    if(config[dataKey].length){
      config.url = config.url + '?userId=' + userId
    } else {
      if(!config[dataKey].userId){
        config[dataKey].userId = userId
      }
    }
  }
  let authorKey = config.headers.authorKey
  if(!authorKey && router.app.$route.name){
    authorKey = router.app.$route.name
  }
  config.headers['charset'] = authorKey ? encrypt(`${authorKey},${config.url}`) : ''
  // delete config[dataKey].authorKey
  delete config.headers.authorKey
  // console.log(authorKey, config.url, 123123)

  return config
}, error => {
  // Do something with request error
  console.log(error); // for debug
  Promise.reject(error)
});

// response 拦截器
service.interceptors.response.use(response => {
  const res = response.data;
  const headers = response.headers;

  if (headers['content-type'] === 'application/vnd.ms-excel;charset=UTF-8') {
    return res
  }
  if (res.status == 200 || res.code == 200 || res.code == '000000') {
    return response.data
  }
  if (response.config.url.indexOf('v1/freight') > -1) {
    return response.data
  }
  if (response.config.headers.extType && response.config.headers.extType === 'excel'){
    return res
  }
  if (response.config.responseType === 'blob') {
    var b = new Blob([res])
    var r = new FileReader()
    r.readAsText(b, 'utf-8')
    r.onload = function () {
      let result = JSON.parse(r.result)
      Message({
        message: result.message || result.msg,
        type: 'error',
        duration: 5 * 1000
      });
    }
  } else {
    if(!response.config.no_err){
      Message({
        message: res.message || res.msg,
        type: 'error',
        duration: 5 * 1000
      })
    }
    // 如果是活动互斥检测
    let checkUrl = response.config.url.indexOf('/fullcut/manage/check')
    if(checkUrl > -1) {
      return response.data
    }
  }

  return Promise.reject('error')
}, error => {
  console.log('err: ' + error); // for debug
  if(!error.config.no_err){
    if (error.response) {
      Message({
        message: error.response.data.message || error.response.data.msg || '服务器异常',
        type: 'error',
        duration: 5 * 1000
      });
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      });
    }
  }
  return Promise.reject(error)
}
);

export default service
